package org.xxpay.manage.sys.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.util.GoogleAuthenticator;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.SysUser;
import org.xxpay.manage.common.ctrl.BaseController;

/**
 * 平台用户安全中心
 */
@RestController
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH + "/security")
public class SecurityCenterController extends BaseController {

    private static final MyLog _log = MyLog.getLog(SecurityCenterController.class);

    /** 得到用户谷歌验证二维码 **/
    @RequestMapping("/google_qrcode")
    public ResponseEntity<?> getGoogleAuthQrCode() {
        _log.info("接收获取谷歌验证码请求, userId={}", getUser().getId());
        try {
            SysUser sysUser = commonService.sysService.findByUserId(getUser().getId());
            String mobile = sysUser.getMobile();
            String googleAuthSecretKey = sysUser.getGoogleAuthSecretKey();
            _log.info("查询到用户googleAuthSecretKey={}", googleAuthSecretKey);
            if(StringUtils.isBlank(googleAuthSecretKey)){
                googleAuthSecretKey = GoogleAuthenticator.generateSecretKey();
                SysUser updateUser = new SysUser();
                updateUser.setUserId(sysUser.getUserId());
                updateUser.setGoogleAuthSecretKey(googleAuthSecretKey);
                int count = commonService.sysService.update(updateUser);
                if(count != 1) return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
            }
            String qrcode = GoogleAuthenticator.getQRBarcode("mgr("+mobile+")", googleAuthSecretKey);

            DBApplicationConfig dbConfig = commonService.sysConfigService.getDBApplicationConfig();
            String qrcodeUrl = dbConfig.getConfig4PayUrl() + "/qrcode_img_get?url=" + qrcode + "&widht=200&height=200";

            JSONObject jsonParams = new JSONObject();
            jsonParams.put("qrcodeUrl", qrcodeUrl);
            jsonParams.put("googleAuthSecretKey", googleAuthSecretKey);
            _log.info("生成谷歌绑定二维码Url={}", qrcodeUrl);
            return ResponseEntity.ok(XxPayResponse.buildSuccess(jsonParams));
        }catch (Exception e) {
            _log.error(e, "生成谷歌绑定二维码异常");
            return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
        }
    }

    /** 绑定谷歌验证  */
    @RequestMapping("/google_bind")
    public ResponseEntity<?> bindGoogleAuth() {

        JSONObject param = getJsonParam();
        // 获取传的验证码
        Long code = getLongRequired(param, "code");

        //当前用户的谷歌验证码， 如有验证失败，提示错误信息
        checkGoogleCode(getUser().getId(), code);

        // 判断当前绑定状态
        SysUser sysUser = commonService.sysService.findByUserId(getUser().getId());
        if (sysUser == null) return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_RECORD_NOT_EXIST));
        if (sysUser.getGoogleAuthStatus() != MchConstant.PUB_NO) return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MGR_STATUS_ERROR));
        // 修改数据中绑定状态
        SysUser updateUser = new SysUser();
        updateUser.setUserId(getUser().getId());
        updateUser.setGoogleAuthStatus(MchConstant.PUB_YES);
        int count = commonService.sysService.update(updateUser);
        if(count != 1) return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_MCH_GOOGLEAUTH_SECRETKEY_BIND_FAIL));
        return ResponseEntity.ok(XxPayResponse.buildSuccess());
    }

}
